package cn.jbolt.ec.rush;

import cn.jbolt.base.JBoltBaseService;
import cn.jbolt.common.model.*;
import cn.jbolt.ec.order.OrderService;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

public class RushCommodityService extends JBoltBaseService<BecRushstoreCommodity> {
    private BecRushstoreCommodity dao = new BecRushstoreCommodity().dao();
    @Inject
    OrderService orderService;

    @Inject
    SysConfigService sysConfigService;

    @Override
    protected BecRushstoreCommodity dao(){
        return dao;
    }

    protected List<BecRushstoreCommodity>
    get_rush_commodities_for_spreader(int retailer_id ){
        Kv cond = Kv.by("credit_stock>",0);
        if(retailer_id>0) cond.set("retailer_id=",retailer_id);
        return getCommonList(cond,"credit_stock","asc",true);

    }

    protected List<BecRushstoreCommodity> get_rush_commodities_for_all(int retailer_id){
        Kv cond = Kv.by("rush_stock>",0);
        if(retailer_id>0) cond.set("retailer_id=",retailer_id);
        return getCommonList(cond,"rush_stock","asc",true);

    }

    /**
     * 全民秒杀订单信息
     * @param client_id
     * @param type
     */
    public List<BecRetailerOrder> rush_order_info(Integer client_id, Integer type){
        Kv cond =Kv.by("client_id",client_id).set("type",type);
        return orderService.getCommonList("id,order_id,order_time,amount_paid,amount_total,charge_id",cond,"id","desc",false);
    }

    /**
     * 全民秒杀订单商品信息
     * @param charge_id
     */
    public List<BecRushstoreCommodity> rush_all_commodity(Integer charge_id){
        Kv cond = Kv.by("id",charge_id);
        return getCommonList("id,market_price,credit_price,rush_price,img_url,commodity_id,commodity_name,retailer_id,retailer_name,option_id,option_title"
                ,cond,"id","desc",false);
    }

    /**
     * 商家获取秒杀商品订单
     * @param retailer_id
     * @param type
     * @return
     */
    public List<BecRetailerOrder> retailer_rush_order_info(Integer retailer_id,Integer type){
        Kv cond = Kv.by("retailer_id",retailer_id).set("type",type);
        return orderService.getCommonList("id,order_id,order_time,amount_paid,amount_total,charge_id",
                cond,"id","desc",false);
    }

    public JSONObject rush_expired(){
        JSONObject jo=new JSONObject();
        String rush_expired= sysConfigService.findById(4).getValue();
        String rush_start= sysConfigService.findById(5).getValue();
        jo.put("rush_expired",rush_expired);
        jo.put("rush_start",rush_start);
        return jo;
    }


    /********************************
     *  以下 为 后台管理方法
     * @author  heqingyu
     * *****************************
     */

    /**
     * 获取 秒杀商品 后台管理主页 分页信息
     * @param pageNum
     * @param pageSize
     * @param keywords
     * @param retailer_id
     * @return
     */
    public Page<BecRushstoreCommodity> get_rush_commodities_page(Integer pageNum,Integer pageSize,String keywords,Integer retailer_id){

        Kv conf = Kv.by("table",table());
        conf.setIfNotBlank("keywords",keywords);
        conf.setIfNotNull("retailer_id",retailer_id);
        return daoTemplate("ec.mall.manage.rush.get_rush_commodities_page",conf).paginate(pageNum,pageSize);
    }


    /**
     * 更新 秒杀商品 价格库存信息
     * @param becRushstoreCommodity
     * @return
     */
    public Ret update_price_stock(BecRushstoreCommodity becRushstoreCommodity,
                                    String credit_price_s,String rush_price_s,
    Integer old_credit_stock,Integer old_rush_stock,Integer user_id ){
        if (becRushstoreCommodity ==null ||becRushstoreCommodity.getId() == null )
            return fail("参数错误");

        Integer credit_price = null;
        Integer rush_price = null;
        if (credit_price_s != null)
            credit_price = Integer_by_String(credit_price_s);
        if (rush_price_s !=null)
            rush_price = Integer_by_String(rush_price_s);
        if (credit_price == null && rush_price == null)
            return fail("操作错误");


        becRushstoreCommodity.setCreditPrice(credit_price);
        becRushstoreCommodity.setRushPrice(rush_price);

        boolean save_lop;
        if (becRushstoreCommodity.getCreditStock() != null && becRushstoreCommodity.getCreditStock()-old_credit_stock!=0){

            save_lop = judge_rush_stock_type(becRushstoreCommodity.getCreditStock(),
                    old_credit_stock,1,becRushstoreCommodity.getCommodityId(),user_id);
            if (!save_lop)
                return fail("日志存储失败");
        }
        if (becRushstoreCommodity.getRushStock() != null && becRushstoreCommodity.getRushStock()-old_rush_stock!=0){

            save_lop = judge_rush_stock_type(becRushstoreCommodity.getRushStock(),
                    old_rush_stock,2,becRushstoreCommodity.getCommodityId(),user_id);
            if (!save_lop)
                return fail("日志存储失败");
        }

        becRushstoreCommodity = judge_price_stock(becRushstoreCommodity);


        boolean success = becRushstoreCommodity.update();
        if (success)
            return  success("操作成功");
        return fail("操作失败");
    }

    public boolean judge_rush_stock_type(Integer new_stock,Integer old_stock,
                                         Integer status,Integer commodity_id, Integer user_id){
        Integer amount = new_stock-old_stock;
        if (amount>0 && status ==1 )
           return rush_stock_add(7,commodity_id,user_id,amount);
        if (amount<0 && status ==1 )
            return rush_stock_add(8,commodity_id,user_id,amount);
        if (amount>0 && status ==2 )
            return rush_stock_add(9,commodity_id,user_id,amount);
        if (amount<0 && status ==2 )
            return rush_stock_add(10,commodity_id,user_id,amount);
        return false;
    }

    public boolean  rush_stock_add(Integer status,Integer commodity_id,
                                   Integer user_id,Integer amount){
        BecRetailerStockChange becRetailerStockChange = new BecRetailerStockChange();
        Long change_time = System.currentTimeMillis();
        becRetailerStockChange.setChangeType(status)
                                .setAmount(amount)
                                .setOperator(user_id)
                                .setCommodityId(commodity_id)
                                .setChangeTime(change_time)
                                .setIsDel(false);

        return becRetailerStockChange.save();


    }


    /**
     * 保存 新增 秒杀商品
     * @param becRushstoreCommodity
     * @return
     */
    public Ret save(BecRushstoreCommodity becRushstoreCommodity ,String credit_price_s,String rush_price_s,Integer user_id){
        if (becRushstoreCommodity == null || notOk(becRushstoreCommodity.getRetailerId()) || notOk(becRushstoreCommodity.getOptionId())
                || notOk(becRushstoreCommodity.getCommodityId()) )
            return fail("参数传入错误");
        Integer credit_price = null;
        Integer rush_price = null;
        if (credit_price_s != null)
            credit_price = Integer_by_String(credit_price_s);
        if (rush_price_s !=null)
            rush_price = Integer_by_String(rush_price_s);
        if (credit_price == null && rush_price == null)
            return fail("操作错误");

        becRushstoreCommodity.setCreditPrice(credit_price);
        becRushstoreCommodity.setRushPrice(rush_price);


        BecRetailer becRetailer_dao = new BecRetailer().dao();
        BecRetailer becRetailer  = becRetailer_dao.findById(becRushstoreCommodity.getRetailerId());
        if (becRetailer == null)
            return fail("未找到该商家，请重新查找");
        String retailer_name = becRetailer.getName();

        BecRetailerCommodity commodity_dao =  new BecRetailerCommodity().dao();
        BecRetailerCommodity commodity =commodity_dao.findById(becRushstoreCommodity.getCommodityId());
        if (commodity == null)
            return fail("未找到该商品，请重新查找");
        String commodity_name = commodity.getName();
        String img_url = commodity.getImage();
        Integer market_price = commodity.getPrice().intValue();

        BecRetailerCommodityOption becRetailerCommodityOption_dao = new BecRetailerCommodityOption().dao();
        BecRetailerCommodityOption becRetailerCommodityOption = becRetailerCommodityOption_dao.findById(becRushstoreCommodity.getOptionId());
        if (becRetailerCommodityOption == null)
            return fail("未找到该商品规格，请重新查找");
        String option_title =becRetailerCommodityOption.getTitle();


        boolean save_lop;
        if (becRushstoreCommodity.getCreditStock() != null){
            save_lop = rush_stock_add(7,becRushstoreCommodity.getCommodityId(),user_id,becRushstoreCommodity.getCreditStock());
            if (!save_lop)
                return fail("日志存储失败");
        }
        if (becRushstoreCommodity.getRushStock() != null){
            save_lop = rush_stock_add(9,becRushstoreCommodity.getCommodityId(),user_id,becRushstoreCommodity.getRushStock());
            if (!save_lop)
                return fail("日志存储失败");
        }

        becRushstoreCommodity = judge_price_stock(becRushstoreCommodity);

        becRushstoreCommodity.setRetailerName(retailer_name);
        becRushstoreCommodity.setCommodityName(commodity_name);
        becRushstoreCommodity.setMarketPrice(market_price);
        becRushstoreCommodity.setImgUrl(img_url);
        becRushstoreCommodity.setOptionTitle(option_title);

        boolean success =  becRushstoreCommodity.save();
        if (success)
            return success("操作成功");
        return fail("操作失败");

    }

    /**
     * 保存和修改时 判断秒杀商品的价格和库存是否为空
     * @param becRushstoreCommodity
     * @return
     */
    public BecRushstoreCommodity judge_price_stock(BecRushstoreCommodity becRushstoreCommodity){
        if (notOk(becRushstoreCommodity.getRushStock())){
            becRushstoreCommodity.setRushStock(0);
            becRushstoreCommodity.setRushPrice(1000000000);
        }


        if (notOk(becRushstoreCommodity.getRushPrice())){
            becRushstoreCommodity.setRushPrice(1000000000);
            becRushstoreCommodity.setRushStock(0);
        }


        if (notOk(becRushstoreCommodity.getCreditStock())){
            becRushstoreCommodity.setCreditStock(0);
            becRushstoreCommodity.setCreditPrice(1000000000);
        }

        if (notOk(becRushstoreCommodity.getCreditPrice())){
            becRushstoreCommodity.setCreditPrice(1000000000);
            becRushstoreCommodity.setCreditStock(0);
        }

        return becRushstoreCommodity;
    }


    /**
     * 删除 秒杀商品
     * @param rush_commodity_id
     * @return
     */
    public Ret delete_rush_commodity(Integer rush_commodity_id){
        if(notOk(rush_commodity_id))
            return fail("参数传入错误");
        BecRushstoreCommodity becRushstoreCommodity = new BecRushstoreCommodity().dao();
        boolean success = becRushstoreCommodity.deleteById(rush_commodity_id);
        if (success)
            return success("操作成功");
        return fail("操作失败");

    }

    /**
     *  切换启用  是否需要会员资格
     * @param id
     * @return
     */
    public Ret toggle_member_required( Integer id) {
        Ret ret=toggleBoolean(id, "member_required");
        if(ret.isOk()){
            return  SUCCESS;
        }
        return FAIL;
    }

    public Integer Integer_by_String(String s){
        Double s_double = Double.parseDouble(s);
        s_double = s_double *100;
        return s_double.intValue();
    }



}
